import { network } from "../../utils/network.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    islyric: false,
    isPlayMusic: false,
    id: 0,
    time1: "00:00",
    time2: "00:00",
    checkTimes: [],
    currentIndex222: 0,
    hang: 0,
    playtime: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;
    var id = options.id;
    if (id){
      that.getData(getApp().globalData.musicid)
    } else {
      wx.request({
        url: 'http://neteasemusic.leanapp.cn/personal_fm',
        success: function (res) {
          console.log("sss")
          console.log(res)
          that.setData({
            songs:res.data.data,
            id:res.data.data[1].id
          })
          getApp().globalData.isFM = true
          id = res.data.data[1].id
          that.playnow(id)
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onmusictap: function (on) {
    var that = this;
    var id = that.data.id;
    if (that.data.isPlayMusic) {
      wx.pauseBackgroundAudio();
      console.log("stop")
    } else {
      wx.playBackgroundAudio({
        dataUrl: that.data.url,
        title: that.data.song.name,
        coverImgUrl: that.data.song.al.picUrl,
      });
      var app = getApp()
      app.globalData.musicid = that.data.id;
      var histories = that.data.histories;
      var isExisted = false;
      if (histories) {
        for (var index = 0; index < histories.length; index++) {
          var savedid = histories[index];
          if (savedid.id === id) {
            isExisted = true;
            break;
          }
        }
      }
      if (!isExisted) {
        if (!histories) {
          histories = [];
        }
        histories.push({ id: id });
        wx.setStorage({
          key: 'played',
          data: histories,
          success: function (res) {
            console.log("保存成功")
            console.log(histories)
          }
        })
      }

      console.log("play")
      let bgMusic = wx.getBackgroundAudioManager();
      bgMusic.onTimeUpdate(() => {
        this.setData({
          time: bgMusic.currentTime,
          alltime: bgMusic.duration,
          time1: this.timeToString(bgMusic.currentTime.toFixed(0)),
          time2: this.timeToString(bgMusic.duration.toFixed(0))
        })
        if (bgMusic.currentTime === bgMusic.duration) {
          this.onLoad()
        }
      })
    }
    getApp().globalData.isPlayMusic = (!that.data.isPlayMusic)
    that.setData({
      isPlayMusic: (!that.data.isPlayMusic)
    })
  },
  onlyrictap: function () {
    var that = this
    that.setData({
      islyric: (!this.data.islyric)
    })
  },

  timeToString: function (duration) {

    let str = '';
    let minute = parseInt(duration / 60) < 10 ? ('0' + parseInt(duration / 60)) : (parseInt(duration / 60));

    let second = (duration % 60) < 10 ? ('0' + duration % 60) : (duration % 60);

    str = minute + ':' + second;

    return str;

  },


  next:function(){
    // wx.pauseBackgroundAudio();
    this.onLoad()
  },

  ontest: function (text) {
    var that = this;
    var result = [];
    var lines = text.split('\n');
    var pattern = /\[\d{2}:\d{2}.\d{2}\]/g;
    var pattern2 = /\[\d{2}:\d{2}.\d{3}\]/g
    var times = [];
    var values = []
    lines[lines.length - 1].length === 0 && lines.pop();
    for (var i = 0; i < lines.length; i++) {
      var time = lines[i].match(pattern);
      var value = lines[i].replace(pattern, '');
      if (!time) {
        time = lines[i].match(pattern2);
        value = lines[i].replace(pattern2, '');
      }
      if (time) {
        time = time[0].slice(1, -1)
        time = time.split(":")
        time = parseInt(time[0] * 60) + parseInt(time[1])
        times.push(time)
        values.push(value)
      }
      that.setData({
        checkTimes: times,
        storyContent: values
      })
    }
  },



  getData: function (id) {
    var that = this
    getApp().globalData.isFM = true;
    wx.request({
      url: 'http://neteasemusic.leanapp.cn/login/cellphone',
      data: {
        phone: 18942883727,
        password: "KanoIA2989657"
      },
      success: function () {
        wx.getStorage({
          key: 'played',
          success: function (res) {
            that.setData({
              histories: res.data,
              isPlayMusic: true
            }),
              network.getDetail({
                id: id,
                success: function (song) {
                  that.setData({
                    song: song,
                  })
                  network.getLyric({
                    id: id,
                    success: function (lrc) {
                      that.setData({
                        lyric: lrc
                      })
                      network.getPlay({
                        id: id,
                        success: function (url) {
                          that.setData({
                            url: url
                          })
                          that.ontest(lrc)
                        },
                      })
                    },
                  })
                }
              })
          },
        })
      }
    })
  },




  playnow:function(id){
    var that=this
    getApp().globalData.isFM = true;
    wx.request({
      url: 'http://neteasemusic.leanapp.cn/login/cellphone',
      data: {
        phone: 18942883727,
        password: "KanoIA2989657"
      },
      success: function () {
        wx.getStorage({
          key: 'played',
          success: function (res) {
            that.setData({
              histories: res.data,
              isPlayMusic:false
            }),
            network.getDetail({
              id: id,
              success: function (song) {
                that.setData({
                  song: song,
                })
                network.getLyric({
                  id: id,
                  success: function (lrc) {
                    that.setData({
                      lyric: lrc
                    })
                    network.getPlay({
                      id: id,
                      success: function (url) {
                        that.setData({
                          url: url
                        })
                        that.onmusictap()
                        that.ontest(lrc)
                      },
                    })
                  },
                })
              }
            })
          },
        })
      }
    })
  },

  onChangeEvent: function (event) {
    var that = this
    let bgMusic = wx.getBackgroundAudioManager();
    var time = event.detail.value / 20000 * bgMusic.duration.toFixed(0)
    wx.seekBackgroundAudio({
      position: time,
    })
    var a = 0;
    for (var i = 0; i < that.data.checkTimes.length; i++) {
      if (time < that.data.checkTimes[i]) {
        a = i
        break;
      }
    }
    that.setData({
      currentIndex222: a,
      hang: a - 1
    })
  }

})